<!--
 * @Descripttion: 上传量尺信息
 * @version:
 * @Author: lehaixia
 * @Date: 2022-10-25 15:12:02
 * @LastEditors: lehaixia
 * @LastEditTime: 2022-11-28 14:02:47
-->
<template>
  <div class="content">
    <ComHeader :title="isAdd?'量尺':'量尺图'" @get-height="handleHeadHeight" />
    <div :class="{'m-no-edit':!isAdd}" style="background:#F8F8FA">
      <van-form @submit="onSubmit">
        <div :class="{'m-form': isAdd}">
          <FieldSelect
            v-if="isAdd"
            v-model="formData.categorySelection"
            required
            :label.sync="formData.categorySelectionName"
            title="品类"
            placeholder="请选择"
            :option-data="categoryTabsList"
            label-name="label"
            value-name="id"
            multiple
            :rules="[
              { required: true, message: '请选择(必选)' }
            ]"
            @change="handleSelect"
          />
          <div class="m-form-field">
            <template v-if="isAdd">
              <Cell v-if="isOnlineCustomer" title="量尺地址" required custom :right="false">
                <div style="color:#16D585" @click.stop="handleLocation">点击{{ locationInfo.addr?'刷新':'获取' }}定位地址</div>
                <div v-if="locationInfo.addr">{{ locationInfo.addr }}</div>
              </Cell>
              <div v-else>
                <van-field v-model="formData.comments" name="comments" type="textarea" placeholder="请输入内容" />
              </div>
            </template>
            <template v-else>
              <div class="m-desc">
                <div>创建人： {{ detailInfo.createBy }}</div>
                <div>创建时间：{{ detailInfo.createTime }}</div>
                <!-- <div>备注：{{ detailInfo.comments }}</div> -->
                <div v-if="isOnlineCustomer">创建地址：{{ locationInfo.addr }}</div>
              </div>
            </template>
            <Cell class="photo-cell" :required="isAdd" custom is-column :right="false">
              <div class="title">
                <span v-if="isAdd" style="color:red;">*</span>
                {{ isAdd?`${isOnlineCustomer?'拍照上传':'上传图片'}`:null }}
                <span v-if="isOnlineCustomer" style="color:red;margin-left:10px;">（现场量尺照片）</span>
              </div>
              <UploadImage
                :image-list="attachmentIdList"
                fit="contain"
                :module-type="moduleType"
                :object-id="objectId"
                :show-album="!isOnlineCustomer"
                :readonly="!isAdd"
                @update="handleUploadImage"
                @delete="handleDeleteImage"
              />
            </Cell>
          </div>
          <FieldDateTime
            v-if="isAdd"
            v-model="formData.expectDrewTime"
            required
            title="出图日期"
            placeholder="请选择"
            type="datetime"
            :default-date="formData.expectDrewTime"
            :min-date="minDate"
            clear
          />
        </div>
        <div v-if="isAdd" class="button-box">
          <van-button type="primary" class="info-button" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
// import { parseTime } from '@/utils'
import Cell from '@/components/ListCell'
import UploadImage from '@/components/UploadImage'
import { saveMeasureInfo, getOptyCategoryData, getMeasureInfo } from '@/apis/optyCategory'
import { getDictByPatchType } from '@/apis/dataDict'
import { queryLocationName } from '@/apis/common'
import { json2FormData } from '@/utils'
import FieldSelect from '@/components/FieldSelect'
import FieldDateTime from '@/components/FieldDateTime'
import { bus } from '@/utils/bus'

export default {
  name: 'MeasureAdd',
  components: {
    Cell, UploadImage, FieldSelect, FieldDateTime
  },
  data() {
    return {
      customerSource: '', // 客户来源：判断是否线上客户
      headHeight: 50,
      minDate: new Date(),
      moduleType: 'Measure',
      objectId: '',
      attachmentIdList: [], // 图片集合
      categoryTabsList: [], // 品类列表
      isAdd: false,
      categoryMap: {},
      formData: {
        id: null,
        categorySelection: [],
        categorySelectionName: '',
        expectDrewTime: '', // parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        comments: ''
      },
      submiting: false,
      detailInfo: '', // 量尺相关信息
      selectedCategoryList: [], // 已选中的品类
      locationInfo: {
        latitude: '', // 纬度
        longitude: '', // 经度
        addr: '' // 地址
      }
    }
  },
  computed: {
    isOnlineCustomer() {
      return this.customerSource === 'Online' // Online 线上， Offline 线下
    }
  },
  async created() {
    const { optyId, optyCategoryId, id, customerSource } = this.$route.query
    this.$set(this.formData, 'id', optyId)

    this.customerSource = customerSource
    this.optyCategoryId = optyCategoryId
    this.isAdd = !id // 是否新增页

    if (this.isAdd) {
      const dictTypeCodes = ['CRM_CATEGORY_SELECTION']
      const dictData = await getDictByPatchType({ dictTypeCodes })
      this.dictData = dictData
      this.categoryList = dictData && dictData.CRM_CATEGORY_SELECTION || []
      this.arrayToObject()
      this.initOptyCategory(optyId)
    } else {
      this.objectId = id
      this.initMeasure(optyId, optyCategoryId, id)
    }
  },
  methods: {
    handleHeadHeight(h) {
      this.headHeight = h
    },
    // 将品类列表转成对象
    arrayToObject() {
      const map = {}
      this.categoryList.forEach(item => {
        const key = item.dictCode
        map[key] = item.dictName
      })
      this.categoryMap = map
    },
    // 已添加品类信息  非终止品类及排除成品
    async initOptyCategory(id) {
      const otherFilters = [{ id: 'optyId', property: 'optyId', value: id, operator: '=' }]
      const sortersRaw = [{ 'id': 'isStop', 'property': 'isStop', 'direction': 'asc' }, { 'id': 'createTime', 'property': 'createTime', 'direction': 'asc' }]
      const data = json2FormData({
        pageFlag: false,
        filtersRaw: JSON.stringify(otherFilters),
        sortersRaw: JSON.stringify(sortersRaw)
      })

      const records = await getOptyCategoryData(data) || []
      records.forEach((v, i) => {
        v.label = this.categoryMap[v.type] || ''
      })
      this.categoryTabsList = records.filter(v => v.isStop === 0 && v.type !== 'FinishedProductFurniture')
    },
    // 获取量尺信息
    initMeasure(optyId, optyCategoryId, id) {
      const otherFilters = [
        { id: 'optyId', property: 'optyId', value: optyId, operator: '=' },
        { id: 'optyCategoryId', property: 'optyCategoryId', operator: '=', value: optyCategoryId },
        { id: 'id', property: 'id', operator: '=', value: id }
      ]
      const data = json2FormData({
        pageFlag: false,
        filtersRaw: JSON.stringify(otherFilters),
        sort: 'createTime',
        order: 'desc'
      })
      getMeasureInfo(data).then(res => {
        const { success, data } = res
        if (success === 1 && data && data.records) {
          const { records = [] } = data
          this.detailInfo = records.length && records[0] || ''
          const attachmentList = records.map(v => v.attachmentList).flat()
          this.$set(this, 'attachmentIdList', attachmentList)
          this.locationInfo = {
            addr: this.detailInfo.addr,
            longitude: this.detailInfo.longitude,
            latitude: this.detailInfo.latitude
          }
        }
      })
    },
    handleSelect(val) {
      this.selectedCategoryList = val
    },
    // 提交
    onSubmit(values) {
      if (this.submiting) return
      const { categorySelection, expectDrewTime } = this.formData

      if (!categorySelection.length) {
        this.$toast('请选择品类')
        return
      }
      if (this.isOnlineCustomer) {
        const none = [undefined, null, '']
        const { latitude, longitude, addr } = this.locationInfo
        if (none.includes(latitude) || none.includes(longitude) || none.includes(addr)) {
          this.$toast('请获取定位地址')
          return
        }
      }
      if (!expectDrewTime) {
        this.$toast('请选择出图日期')
        return
      }
      if (this.attachmentIdList.length === 0) {
        this.$toast('请添加图片')
        return
      }
      const attachmentIdList = this.attachmentIdList.map(v => v.id) // 上传图片信息
      const measureInfoDto = categorySelection.map(v => { return { optyCategoryId: v, ...this.locationInfo } })
      const data = {
        ...this.formData,
        isOnline: this.isOnlineCustomer,
        measureInfoDto,
        attachmentIdList
      }
      this.submiting = true
      saveMeasureInfo(data).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$toast(res.msg || '提交成功')
          this.$router.go(-1)

          const isAllStage = this.selectedCategoryList.some(v => v.stage === 'MeasuringScale') // 如果选中的品类含有 量尺，新增后则需要更新品类状态
          bus.$emit('refreshCustomerItem', {
            title: '新增量尺图',
            type: 'addMeasure',
            isRefreshCategory: isAllStage
          })
        }
      }).catch(() => {
        this.submiting = false
        this.$toast('提交失败')
      })
    },
    // 更新图片
    handleUploadImage(data) {
      this.$set(this, 'attachmentIdList', data)
      if (!this.isAdd) {
        this.$nextTick(() => {
          bus.$emit('refreshCustomerItem', {
            title: '编辑量尺图',
            type: 'editMeasure'
          })
        })
      }
    },
    // 删除图片
    handleDeleteImage() {

    },

    scientificToNumber(inputNumber) {
      if (isNaN(inputNumber)) {
        return inputNumber
      }
      inputNumber = '' + inputNumber
      inputNumber = parseFloat(inputNumber)
      const eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式（字符串）
      const tmpArray = eformat.match(/\d(?:\.(\d*))?e([+-]\d+)/) // 分离出小数值和指数值
      const number = inputNumber.toFixed(Math.max(0, (tmpArray[1] || '').length - tmpArray[2]))
      return number
    },
    async demoAddress() {
      const params = {
        latitude: '30.685760982666373',
        longitude: '103.95943001623395'
      }
      const address = await queryLocationName(params)
      this.locationInfo = { ...params, addr: address }
    },
    handleLocation() {
      /* this.demoAddress()
      return */
      const loading = this.$toast.loading({
        forbidClick: true,
        message: '定位获取中...',
        duration: 0
      })
      const data = {
        isSingle: true, // 单次定位 非必传 默认 true
        overtime: 30, // 超时时间 非必传 默认 60
        minTime: 1, // 最小刷新时间 非必传 isSingle=false 生效 默认5
        minDistance: 0 // 最小刷新距离 非必传 isSingle=false 生效 默认0.5
      }
      this.$nativeHandler('requestLocation', JSON.stringify(data)).then(async(res) => {
        // 单次定位或实时定位首次 成功结果
        // console.log('获取定位成功', res)
        // console.log(res.latitude, res.longitude, res.provider, res.time, res.accuracy)
        // 通过经纬度获取详细地址
        const params = {
          latitude: this.scientificToNumber(res.latitude),
          longitude: this.scientificToNumber(res.longitude)
        }
        const address = await queryLocationName(params)
        this.locationInfo = { ...params, addr: address }
        loading.clear()
      }).catch((error) => {
        // 开启定位失败
        console.log(error)
        loading.clear()
      })
      setTimeout(() => {
        loading.clear()
      }, 5000)
    }
  }
}
</script>
<style lang="less" scoped>
.m-form {
  padding-bottom: 70px;
}

.m-no-edit {
  padding: 11px 16px;
}
.m-form-field {
  // min-height: 370px;
  background: #FFFFFF;
  margin-bottom: 10px;

  ::v-deep .van-field__control::-webkit-input-placeholder {
    font-size: 14px;
    font-weight: 400;
    color: #3C4458;
    line-height: 20px;
  }
  ::v-deep  .van-cell::after {
    display: none;
  }

  .m-desc {
    padding: 16px 16px 0;
    &>div {
      font-size: 14px;
      font-weight: 500;
      color: #3C4458;
      line-height: 20px;
      letter-spacing: 1px;
      margin-bottom: 8px;
      &:nth-last-of-type(1) {
        margin-bottom: 0;
      }
    }
  }
  .upload-class {
    padding: 16px;
  }
}
.button-box {
  position: fixed;
  bottom: 0;
  width: calc(100vw - 32px);
  height: 58px;
  left: 16px;
  .info-button {
    width: 100%;
    background: linear-gradient(270deg, #009E77 0%, #20CE92 100%);
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    color: #FFFFFF;
    height: 48px;
    line-height: 22px;
    /deep/ .van-button--disabled {
      opacity: .4;
    }
  }
}
/deep/ .photo-cell{
  .title{
    margin-left: -5px;
    margin-bottom: 10px;
  }
   .value{
    overflow:unset;
  }
}
</style>
